<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\SiteRequest;
use App\Models\Area;
use App\Models\User;
use App\Models\XcDevice;
use App\Models\XcFactoryWashMode;
use App\Models\XcRenter;
use App\Models\XcSite;
use App\Models\XcSiteWashMode;
use App\Models\XcFactory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\RenterRequest;

/***
 * 站点控制层
 *
 */
class SiteController extends Controller
{

    /**
     * 站点列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $renter_id     = $request->get("renter_id",0);
        $renter = XcRenter::where('id', $renter_id)->first();
        $citycode = $provincecode = "";
        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        if ($crole_name[0]['name'] == "root"){
            $citys = GetCitys();
        }else{
            $citys = GetCitys($citycode);
        }

        return View::make('admin.site.index',compact('citys', 'renter','renter_id'));
    }

    /**
     * 获得声租方列表数据，分页信息
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        //$data = $request->all();
        $renter_id = $request->get("renter_id");
        $renter = XcSite::where("renter_id", $renter_id);

        $res = $renter->orderBy('id','desc')->with("device")->paginate($request->get('limit',10));
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    /**
     * 新建站点视图
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function create(Request $request)
    {
        $renter_id     = $request->get("renter_id",0);
        $citys = [];
        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        $provincecode = $citycode = "";

        if ($crole_name[0]['name'] == "root"){
            $citys = GetCitys();
        }else{
            $citys = GetCitys($citycode);
        }

        return View::make('admin.site.create', compact('citys','citycode', 'provincecode',"renter_id"));
    }

    /**
     * 保存站点信息数据
     *
     * @param RenterRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(SiteRequest $request)
    {
        $user = Auth::guard('web')->user();
        $data = $request->validated();
        $data['cuser_id'] = $user->id;

        //dd($data);
        try{
            $renter = XcSite::create($data);
            //return Redirect::to(URL::route('admin.site',['id' => $data['renter_id']]))->with(['success'=>'创建成功']);
            return '<script>window.parent.layer.closeAll();
                        window.parent.layer.msg("创建成功");
                        window.parent.layui.table.reload("dataTable");</script>';
        }catch (\Exception $exception){
            return Redirect::back()->withErrors($exception->getMessage());
        }
    }


    /**
     * 站点信息编辑
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(Request $request)
    {
        $id = $request->get("id");
        $crole_name = Auth::user()->roles()->get()->toArray()??"";
        $provincecode = $citycode = "";

        $site = XcSite::where("id", $id)->first();
        //dd($site);
        $renter_id = $site->renter_id;
        $citycode = $site->city_code;
        if (!empty($citycode)){
            $area = Area::where([["code",'=',$citycode],['leveltype','=',1]])->first();
            $provincecode = $area->supcode;
        }
        //dd($provincecode);

        if ($crole_name[0]['name'] == "root"){
            $citys = GetCitys();
        }else{
            $citys = GetCitys($citycode);
        }

        return View::make('admin.site.edit', compact("citys", "provincecode", "citycode", "site", "renter_id"));
    }

    /**
     * 更新站点信息数据
     *
     * @param RenterRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(SiteRequest $request)
    {
        $id   = $request->get("id");
        $data = $request->validated();

        try{
            XcSite::where("id", $id)->update($data);

            return Redirect::to(URL::route('admin.site',['renter_id'=>$data['renter_id']]))->with(['success'=>'更新成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors($exception->getMessage());
        }
    }

    /**
     * 删除站点信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (!is_array($ids) || empty($ids)){
            return Response::json(['code'=>1,'msg'=>'请选择删除项']);
        }
        try{
            //目前采用逻辑删除
            XcSite::whereIn('id', $ids)->update(['status' => -1]);
            return Response::json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            return Response::json(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }

    /**
     * 站点绑定设备
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function binddevice(Request $request)
    {
        $id = $request->get("id");
        $washmodel_arra = [];
        $mode_ids_str = "";
        $device_no = $factory_name = $device_model = "";
        $site = XcSite::where("id",$id)->with(["device" => function ($q){
                    $q->with("factory");
                },"washmode" => function($query){
                    $query->with("factorywashmode");
                }])->get()->toArray();
        $site = $site[0];
        //dd($site);
        if (!empty($site['device'])){
            //$factory_id = $site['device'][0]['factory_id'];
            $washmodel_arra_temp = $site['washmode'];
            $temp_arra = [];
            foreach ($washmodel_arra_temp as $key => $value) {
                $temp_arra[] = $value['fw_id'];
                $washing_type = $value['washing_type']??0;
                $washmodel_arra[$washing_type] = [
                            'qs_price'      => $value['qs_price'],
                            'pm_price'      => $value['pm_price'],
                            'xc_price'      => $value['xc_price'],
                            'xs_price'      => $value['xs_price'],
                            'xd_price'      => $value['xd_price'],
                            'default_flag'  => $value['default_flag']
                            ];
            }
            if (!empty($temp_arra)) $mode_ids_str = implode(",", $temp_arra);

            $device_no = $site['device']['device_no']??"";
            $factory_name = $site['device']['factory']['name']??"";
            $device_model = $site['device']['device_model']??"";
        }


        $arra = XcFactory::GetXcModel();
        $washmode = ArrayReplaceIndex($arra, "key");

        $factory_washmode = [];
        $factory_id = $site['device']['factory_id']??0;
        if ($factory_id > 0){
            $factory_washmode = XcFactoryWashMode::where("factory_id", $factory_id)->get();
        }
        //dd($factory_washmode->toArray());


        return View::make('admin.site.binddevice',compact('id','site','device_no', 'factory_name', 'device_model', 'washmodel_arra','mode_ids_str','washmode','factory_washmode'));
    }

    /**
     * 通过设备编号获得设备的数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getdeviceinfo(Request $request)
    {
        $device_no = $request->get("device_no");
        $res = XcDevice::where([['device_no','=',$device_no],['renter_id','=',0],['site_id', '=', 0]])
                ->with(["factory" => function($q){
                    $q->with("washmode");
                }])->get()->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'data'  => $res[0]??'',
        ];
        return Response::json($data);
    }

    /**
     * 保存绑定数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storebinddevice(Request $request)
    {
        $data = $request->all();
        //dd($data);
        $device_id = $data['device_id'];
        $sitemode_arra = [];
        if (!empty($data['fw_id'])){
            foreach ($data['fw_id'] as $k => $v) {
                $washing_type = $data['washing_type'.$v]??1;
                $default_flag = 0;
                if (count($data['fw_id']) > 0 && $k == 0)  $default_flag = 1;
                $sitemode_arra[] = ['renter_id'     => $data['renter_id'],
                                    'site_id'       => $data['site_id'],
                                    'fw_id'         => $v,
                                    //'washing_type'  => $washing_type,
                                    'qs_price'      => $data['qs_price'.$washing_type],
                                    'pm_price'      => $data['pm_price'.$washing_type],
                                    'xc_price'      => $data['xc_price'.$washing_type],
                                    'xs_price'      => $data['xs_price'.$washing_type],
                                    'xd_price'      => $data['xd_price'.$washing_type],
                                    'default_flag'  => $default_flag,
                                    'created_at'    => date("Y-m-d H:i:s"),
                                    'updated_at'    => date("Y-m-d H:i:s")
                                    ];
            }
        } 
        //dd($sitemode_arra);

        //首先绑定设备，修改设备renter_id,site_id值
        DB::beginTransaction();
        try{

            //目前采用逻辑删除
            XcDevice::where('id', $device_id)->update(['renter_id' => $data['renter_id'], 'site_id' => $data['site_id']]);
            //把站点收费收费规则数据写入表
            if (!empty($sitemode_arra)){
                XcSiteWashMode::where(['renter_id' => $data['renter_id'], 'site_id' => $data['site_id']])->delete();
                XcSiteWashMode::insert($sitemode_arra);
            } 

            XcSite::where('id', $data['site_id'])->update(['install_time' => $data['install_time']]);
            //return Response::json(['code'=>0,'msg'=>'绑定成功']);
            DB::commit();
            return '<script>window.parent.layer.closeAll();
                        window.parent.layer.msg("创建成功");
                        window.parent.layui.table.reload("dataTable");</script>';
        }catch (\Exception $exception){
            DB::rollback();
            //return Response::json(['code'=>1,'msg'=>'绑定失败','data'=>$exception->getMessage()]);
            return '<script>window.parent.layer.closeAll();
                        window.parent.layer.msg("绑定失败");
                        window.parent.layui.table.reload("dataTable");</script>';
        }
    }
}